package com.sinosoft.flow.service.impl;

import com.sinosoft.flow.service.MyProcessService;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.engine.RepositoryService;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;

/**
 * @Author: njz
 * @Description:
 * @Date: create in 2022/2/11 11:26
 */
@Service
public class MyProcessServiceImpl implements MyProcessService {

    @Autowired
    private RepositoryService repositoryService;

    @Qualifier("processEngine")
    @Autowired
    private ProcessEngine processEngine;


    /**
     * 查 act_re_procdef 表 id
     * @param proicessDefinitionId
     * @param response
     */
    //TODO 中文乱码
    @Override
    public void getProcessView(String proicessDefinitionId, HttpServletResponse response) throws UnsupportedEncodingException {
        BpmnModel bpmnModel = repositoryService.getBpmnModel(proicessDefinitionId);
        ProcessEngineConfiguration processEngineConfiguration=processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator processDiagramGenerator=new DefaultProcessDiagramGenerator();
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("1.png", "UTF-8"));
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        try(
                InputStream in=processDiagramGenerator.generateDiagram(bpmnModel,"png", Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                        processEngineConfiguration.getActivityFontName(), processEngineConfiguration.getLabelFontName(),
                        processEngineConfiguration.getAnnotationFontName(), processEngineConfiguration.getClassLoader(),
                        1.0,true);
                OutputStream out=response.getOutputStream();
        ){
            byte[] buffer=new byte[2048];
            int length;
            while( (length = in.read(buffer)) != -1){
                out.write(buffer,0,length);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
